package com.pzl.horizontallistview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by zl.peng on 2016-02-24.
 */
public class MyAdapter extends BaseAdapter {
    private Context context;
    private Drawable[] drawables;

    public MyAdapter(Context context, Drawable[] drawables) {
        this.context = context;
        this.drawables = drawables;
    }

    @Override
    public int getCount() {
        if (drawables != null && drawables.length != 0) {
            return drawables.length;
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return drawables[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
            viewHolder = new ViewHolder(convertView);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // viewHolder.getIv_bg().setBackgroundResource(data[position]);//该方法在getview非常影响性能
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            viewHolder.getIv_bg().setBackground(drawables[position]);
        } else {
            viewHolder.getIv_bg().setImageDrawable(drawables[position]);
        }
        viewHolder.getTv_title().setText("title" + position);
        return convertView;
    }

    class ViewHolder {
        private ImageView iv_bg;
        private TextView tv_title;
        private View root;

        public ViewHolder(View root) {
            this.root = root;
            root.setTag(this);
        }

        public ImageView getIv_bg() {
            if (iv_bg == null) {
                iv_bg = (ImageView) root.findViewById(R.id.iv_bg);
            }
            return iv_bg;
        }

        public TextView getTv_title() {
            if (tv_title == null) {
                tv_title = (TextView) root.findViewById(R.id.tv_title);
            }
            return tv_title;
        }
    }
}
